package cn.tedu._14vehicle703.base.exception;

import cn.tedu._14vehicle703.base.response.JsonResult;
import cn.tedu._14vehicle703.base.response.StatusCode;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException ex) {
        String data = ex.getMessage();
        log.debug("IllegalArgumentException:" + data);
        return new JsonResult(StatusCode.OPERATION_FAILED, data);
    }

    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex){
        /*
            默认异常提示消息格式: del.id: 车辆id必须在1-500之间
            ex.getMessage().split(":")[0].trim()得到结果：车辆id必须在1-500之间
         */
        String data = ex.getMessage().split(":")[1].trim();
        log.error("ConstraintViolationException:" + data);
        return new JsonResult(StatusCode.VALIDATED_ERROR, data);
    }
}
